package com.yunfeisoft.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.applet.utils.KeyUtils;
import com.applet.utils.SpringContextHelper;
import com.yunfeisoft.business.model.Customer;
import com.yunfeisoft.business.service.inter.CustomerService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class CustomerExcelListener extends AnalysisEventListener<Customer> {

    private static final Logger logger = LoggerFactory.getLogger(CustomerExcelListener.class);

    private List<Customer> list = new ArrayList<Customer>();
    private String orgId;
    private String userId;

    public CustomerExcelListener(String orgId, String userId) {
        this.orgId = orgId;
        this.userId = userId;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param customer
     * @param analysisContext
     */
    @Override
    public void invoke(Customer customer, AnalysisContext analysisContext) {
        if (StringUtils.isBlank(customer.getName())) {
            return;
        }
        customer.setId(KeyUtils.getKey());
        customer.setOrgId(orgId);
        customer.setCreateId(userId);
        customer.setModifyId(userId);
        customer.setBalance(customer.getBalance() == null ? BigDecimal.ZERO : customer.getBalance());

        String typeStr = customer.getTypeStr();
        if ("零售客户".equals(typeStr)) {
            customer.setType(Customer.CustomerTypeEnum.RETAIL.getValue());
        } else if ("会员客户".equals(typeStr)) {
            customer.setType(Customer.CustomerTypeEnum.MEMBER.getValue());
        } else if ("批发客户".equals(typeStr)) {
            customer.setType(Customer.CustomerTypeEnum.WHOLESALE.getValue());
        }

        list.add(customer);
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }

        CustomerService customerService = SpringContextHelper.getBean(CustomerService.class);
        customerService.batchSave(list);
    }
}
